const express = require('express')
const expressWs=require('express-ws')
const app = express()
expressWs(app)

app.use(express.static('public'))

// 用于存储所有已连接的客户端
const clients = [];

app.ws('/', (ws) => {
      // 当有新客户端连接时，将其添加到 clients 数组中
    clients.push(ws);
    
    ws.on('message', (data) => {
        console.log(data);
        
         // 遍历除了发送者（当前 ws）之外的所有客户端，发送消息
    clients.filter(client => client!== ws).forEach(client => {
        client.send(data);
    });
        
        // ws.send(data)
        
    }) 

    ws.on('close', () => {
        // 当客户端断开连接时，从 clients 数组中移除该客户端
        const index = clients.findIndex(client => client === ws);
        if (index > -1) {
          clients.splice(index, 1);
        }
      });
})

app.listen(4500, () => {
    console.log('server is running at 4500');
    
})
